import { Button, Input, message, Modal, Radio, Select } from 'antd';
import { connect } from 'dva';
import { is } from 'immutable';
import React from 'react';
import styles from './index.less';

const { TextArea } = Input;
const presetParams = [
  { param: '【商户客服电话】', presetLength: 14 },
  { param: '【未启动天数】', presetLength: 3 },
  // { param: "【行驶里程监控天数】", presetLength: 3 },
  // { param: "【行驶里程】", presetLength: 6 },
  { param: '【逾期天数】', presetLength: 3 },
  { param: '【离开管控区域天数】', presetLength: 3 },
  { param: '【T-BOX失联天数】', presetLength: 3 },
];
/**
 * 换算当前内容字符串长度 -> 计算长度
 * @returns 计算后的长度
 */
const convertIntoCalcLength = (str) => {
  let calcLength = str.length;
  presetParams.map((item) => {
    const reg = new RegExp(`${item.param}`, 'g');
    if (str.match(reg))
      calcLength += str.match(reg).length * (item.presetLength - item.param.length);
  });
  return calcLength;
};
/**
 * 查找所有匹配项-参数名称和起止下标
 * @returns
 */
const getMatchedParams = (str) => {
  const patterns = presetParams.map((item) => {
    return `${item.param}`;
  });
  const reg = new RegExp(patterns.join('|'), 'g');
  const matchedParams = [];
  str.replace(reg, (result, offset) => {
    // console.log(result, offset);
    matchedParams.push({
      param: result,
      startIdx: offset,
      endIdx: offset + result.length,
    });
  });
  return matchedParams;
};
/**
 * 空格转换为html
 */
const formatText2Html = (text) => {
  let html = text;
  if (html) {
    html = html.replace(/ /g, '&nbsp;');
  }
  return html;
};
@connect((state) => ({
  merchantsData: state.menu.merchantsData
}))
export default class AddModal extends React.PureComponent {

  constructor(props) {
    super(props);
    const { merchantsData } = this.props;
    this.state = {
      submitBtnLoading: false,
      //车机
      name: '',
      warnTitle: '温馨提示',
      titleMaxNum: 9,
      showType: String(merchantsData.type) === '1' ? 3 : 2,
      ttsVoiceFlag: String(merchantsData.type) === '1' ? 1 : 0,
      warnContent: '您的车辆已触发风控，请规范用车，谢谢。',
      ttsContent: '您的车辆已触发风控，请规范用车，谢谢。',
      contentMaxNum: String(merchantsData.type) === '1' ? 70 : 40,
      warnContentCalcNum: 19,
      ttsContentCalcNum: 19,
      compositionTypingFlag: false, //  是否是中文输入中
      contentTypingFlag: false,
      // keywords: [
      //   { word: "【商户客服电话】", length: 14 },
      //   { word: "【未启动天数】", length: 3 },
      //   { word: "【行驶里程监控天数】", length: 3 },
      //   { word: "【行驶里程】", length: 6 },
      //   { word: "【逾期天数】", length: 3 },
      //   { word: "【离开管控区域天数】", length: 3 },
      //   { word: "【T-BOX失联天数】", length: 3 },
      // ],
      useType: String(merchantsData.type) === '1' ? 2 : 3,
      isDisabled: String(merchantsData.type) === '1',
    };
  }
  componentDidMount() {
    setTimeout(() => {
      const { ttsContent } = this.state;
      const ele = document.getElementById('text-area1');
      const ele1 = document.getElementById('text-area2');
      ele.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';
      ele1.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';

      const tts1 = document.getElementById('text-area3');
      const tts2 = document.getElementById('text-area4');
      tts1 && (tts1.innerHTML = ttsContent);
      tts2 && (tts2.innerHTML = ttsContent);
    });
  }

  handleSubmit = () => {
    const { changeAddModalVisible } = this.props;
    const { name, warnTitle, showType, ttsVoiceFlag, warnContent, ttsContent, useType } =
      this.state;
    if (!name.trim()) {
      message.error('告警规则名称不能为空');
      return;
    }

    if (!warnTitle.trim()) {
      message.error('标题不能为空');
      return;
    }

    if (!warnContent) {
      message.error('车机告警内容不能为空');
      return;
    }
    if (!!ttsVoiceFlag && !ttsContent) {
      message.error('TTS语音播报内容不能为空');
      return;
    }
    const params = {
      name,
      warnTitle,
      showType,
      ttsVoiceFlag,
      warnContent,
      useType,
    };
    params['ttsContent'] = !!ttsVoiceFlag ? ttsContent : '';
    this.setState({
      submitBtnLoading: true,
    });
    this.props.dispatch({
      type: 'deviceWarningRules/postObjWithRes',
      payload: {
        url: '/mscreditbusiness/iviNotice/save',
        ...params,
      },
      callback: (response) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          changeAddModalVisible(true);
          // } else {
          //   message.error(response.statusMessage);
        }
        this.setState({
          submitBtnLoading: false,
        });
      },
    });
  };

  handleHtml = (text) => {
    // const { keywords } = this.state;
    let a = text;
    let calcNum = text.length;
    presetParams.map((item) => {
      const str = item.param;
      const tihan = `<span>${str}</span>`;
      const reg = new RegExp(`${str}`, 'g');
      if (a.match(reg)) calcNum += a.match(reg).length * (item.presetLength - str.length);
      a = a.replace(reg, tihan);
    });
    const html = formatText2Html(a);
    return { html, calcNum };
  };

  /**
   * 处理输入文字
   * @param {*} id1
   * @param {*} id2
   * @param {*} type
   */
  handleContentText = (id1, id2, type) => {
    const { contentMaxNum, contentTypingFlag, compositionTypingFlag } = this.state;
    const ele = document.getElementById(id1);
    const ele2 = document.getElementById(id2);
    // const ele3 = document.getElementById(pid);
    // ele3.style.height = `${ele.offsetHeight}px`;
    // let oldHtml = ele.innerHTML;
    let oldText = ele.innerText;
    const reg1 = new RegExp('<span>', 'g');
    const reg2 = new RegExp('</span>', 'g');

    // oldHtml = oldHtml.replace(reg1, "");
    // oldHtml = oldHtml.replace(reg2, "");
    const result = this.handleHtml(oldText);
    let newHtml = result.html;
    let calcNum = result.calcNum;
    // 输入结束 或 中文输入结束
    if (!contentTypingFlag || !compositionTypingFlag) {
      if (calcNum > contentMaxNum) {
        //自定义截取
        const sliceIdx = this.getSliceIndex(oldText);
        oldText = oldText.substring(0, sliceIdx);
        // oldHtml = formatText2Html(oldText);
        const result1 = this.handleHtml(oldText);
        newHtml = result1.html;
        let bHtml = newHtml.replace(reg1, '');
        bHtml = bHtml.replace(reg2, '');
        ele.innerHTML = bHtml;
        ele.blur();
      } else if (calcNum === contentMaxNum) {
        let bHtml = newHtml.replace(reg1, '');
        bHtml = bHtml.replace(reg2, '');
        ele.innerHTML = bHtml;
        ele.blur();
      }
      calcNum = this.handleHtml(oldText).calcNum;
      oldText = ele.innerText;

      if (type === 'warn') {
        // 告警内容
        this.setState({
          warnContent: oldText,
          warnContentCalcNum: calcNum,
        });
      } else if (type === 'tts') {
        // tts内容
        this.setState({
          ttsContent: oldText,
          ttsContentCalcNum: calcNum,
        });
      }
    }
    ele2.innerHTML = newHtml;
  };

  onEditorStatePaste = async (e) => {
    e.preventDefault();
    // if (navigator.clipboard) {
    //   const res = await navigator.clipboard.readText();
    //   console.log("粘贴", res);
    //   // e.preventDefault();
    // }
  };
  /**
   * 处理截取，返回实际截取字符串下标
   * @returns
   */
  getSliceIndex = (str) => {
    const { contentMaxNum } = this.state;
    const matchedParams = getMatchedParams(str);
    let result;
    const arr = str.split('');
    arr.some((char, idx) => {
      result = idx;
      const currStr = str.substring(0, idx + 1); //  获取当前位置的对应截取字符串
      const currCalcStrLength = convertIntoCalcLength(currStr); //  获取当前截取字符串计算后的长度
      // 若当前截取段的计算长度大于最大限制
      if (currCalcStrLength > contentMaxNum) {
        // 判断:
        //  1、当前位置 idx 是否介于某匹配项的起止位置间，
        //  2、换算长度小于匹配参数实际长度（即：匹配到末尾后计算长度变小）
        //  3、当前截取段的计算长度 + 匹配参数项的换算长度补齐 <= 最大限制
        //  -继续遍历
        // 否则，停止遍历 返回idx
        const matchedParam = matchedParams.find(
          (param) => param.startIdx <= idx && param.endIdx >= idx,
        );
        const currParam =
          matchedParam && presetParams.find((item) => item.param === matchedParam.param);
        if (
          matchedParam &&
          currParam.presetLength < currParam.param.length &&
          currCalcStrLength + (matchedParam.endIdx - idx) <= contentMaxNum
        ) {
        } else {
          return true;
        }
      }
    });
    return result;
  };
  render() {
    const {
      submitBtnLoading,
      name,
      warnTitle,
      titleMaxNum,
      showType,
      ttsVoiceFlag,
      contentMaxNum,
      warnContentCalcNum,
      ttsContentCalcNum,
      useType,
      isDisabled,
    } = this.state;

    const { changeAddModalVisible, merchantsData } = this.props;
    const useTypeOpt = String(merchantsData.type) === '1' ?
      [{ label: '锁车', value: 2 }] :
      [
        { label: '跛行', value: 1 },
        { label: '锁车', value: 2 },
        { label: '其他', value: 3 },
      ]
    return (
      <Modal
        title="新建车机告警规则"
        style={{ top: 15 }}
        onCancel={() => changeAddModalVisible(false)}
        visible={true}
        footer={[
          <Button key="back" type="ghost" size="small" onClick={() => changeAddModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            size="small"
            loading={submitBtnLoading}
            onClick={() => this.handleSubmit()}
          >
            提交
          </Button>,
        ]}
      >
        <div className={styles.addModal}>
          <div className={styles.publicItem}>
            <div className={styles.itemTitle}>请输入告警规则名称:</div>
            <div className={styles.itemContent}>
              <Input
                value={name}
                placeholder={'请输入告警规则名称'}
                onChange={(e) => {
                  this.setState({
                    name: e.target.value,
                  });
                }}
              />
            </div>
          </div>
          <div className={styles.publicItem}>
            <div className={styles.itemTitle}>请选择使用场景:</div>
            <div className={styles.itemContent}>
              <Radio.Group
                options={useTypeOpt}
                onChange={(e) => {
                  const isDisabled = e.target.value === 3 ? false : true;
                  this.setState({
                    useType: e.target.value,
                    isDisabled: isDisabled,
                  });
                  if (isDisabled) {
                    this.setState({
                      warnTitle: '温馨提示',
                      showType: 3,
                      ttsVoiceFlag: 1,
                      titleMaxNum: 37,
                      contentMaxNum: 70,
                      ttsContent: '您的车辆已触发风控，请规范用车，谢谢。',
                    });
                    setTimeout(() => {
                      const ele = document.getElementById('text-area3');
                      const ele1 = document.getElementById('text-area4');
                      ele.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';
                      ele1.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';
                    });
                  }
                }}
                value={useType}
              />
            </div>
          </div>
          <span style={{ color: isDisabled ? 'rgba(0, 0, 0, 0.25)' : 'rgba(0, 0, 0, 0.65)' }}>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>请填写标题:</div>
              <div className={styles.itemContent}>
                <TextArea
                  value={warnTitle}
                  placeholder={`请输入最多${titleMaxNum}个字的标题`}
                  maxLength={titleMaxNum}
                  onChange={(e) => {
                    this.setState({
                      warnTitle: e.target.value,
                    });
                  }}
                  disabled={isDisabled}
                />
                <span className={styles.suffixNum}>
                  {warnTitle.length}/{titleMaxNum}
                </span>
              </div>
            </div>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>请选择告警显示方式:</div>
              <div className={styles.itemContent}>
                <Radio.Group
                  options={[
                    { label: '弱提醒', value: 1 },
                    { label: '弹框提醒', value: 2 },
                    { label: '霸屏提醒', value: 3 },
                  ]}
                  onChange={(e) => {
                    const titleMaxNum = e.target.value === 3 ? 37 : 9;
                    const contentMaxNum = e.target.value === 3 ? 70 : 40;
                    this.setState(
                      {
                        showType: e.target.value,
                        titleMaxNum,
                        contentMaxNum,
                        warnTitle: warnTitle.substring(0, titleMaxNum),
                      },
                      () => {
                        this.handleContentText('text-area1', 'text-area2', 'warn');
                        if (!!ttsVoiceFlag) {
                          // 开启tts
                          setTimeout(() => {
                            this.handleContentText('text-area3', 'text-area4', 'tts');
                          });
                        }
                      },
                    );
                  }}
                  value={showType}
                  disabled={isDisabled}
                />
              </div>
            </div>
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>是否开启TTS语音播报:</div>
              <div className={styles.itemContent}>
                <Radio.Group
                  options={[
                    { label: '不开启', value: 0 },
                    { label: '开启', value: 1 },
                  ]}
                  onChange={(e) => {
                    this.setState({
                      ttsVoiceFlag: e.target.value,
                      ttsContent: e.target.value ? '您的车辆已触发风控，请规范用车，谢谢。' : '',
                    });
                    if (!!e.target.value) {
                      setTimeout(() => {
                        const ele = document.getElementById('text-area3');
                        const ele1 = document.getElementById('text-area4');
                        ele.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';
                        ele1.innerHTML = '您的车辆已触发风控，请规范用车，谢谢。';
                      });
                    }
                  }}
                  value={ttsVoiceFlag}
                  disabled={isDisabled}
                />
              </div>
            </div>
          </span>
          <div className={styles.publicItem}>
            <div className={styles.itemTitle}>请填写告警内容:</div>
            {/* <div className={styles.itemContent}>
              <TextArea
                value={warnContent}
                placeholder={`请输入最多${contentMaxNum}个字的告警内容`}
                maxLength={contentMaxNum}
                autoSize={{ minRows: 2 }}
                onChange={(e) => {
                  this.setState({
                    warnContent: e.target.value,
                  });
                }}
              />
              <span className={styles.suffixNum}>
                {warnContentCalcNum.length}/{contentMaxNum}
              </span>
            </div> */}
            <div id="text-Content1" className={styles.itemContent2}>
              <div
                className={styles.textContent1}
                onPaste={this.onEditorStatePaste}
                id="text-area1"
                onCompositionStart={() => {
                  this.setState({
                    compositionTypingFlag: true,
                  });
                }}
                onCompositionEnd={() => {
                  this.setState({
                    compositionTypingFlag: false,
                  });
                }}
                onKeyDown={(e) => {
                  e.keyCode === 13 && e.preventDefault(); //  禁止回车事件，影响字数统计
                }}
                onInput={() => {
                  this.setState({
                    contentTypingFlag: true,
                  });
                  setTimeout(() => {
                    this.handleContentText('text-area1', 'text-area2', 'warn');
                  });
                }}
                onBlur={() => {
                  this.setState(
                    {
                      compositionTypingFlag: false,
                      contentTypingFlag: false,
                    },
                    () => {
                      this.handleContentText('text-area1', 'text-area2', 'warn');
                    },
                  );
                }}
                contentEditable
                placeholder={`请输入最多${contentMaxNum}个字的告警内容`}
              ></div>
              <div
                onPaste={(e) => {
                  e.preventDefault();
                }}
                id="text-area2"
                className={styles.textContent2}
              ></div>
              <span
                className={
                  warnContentCalcNum > contentMaxNum
                    ? styles.customSuffixWarningNum
                    : styles.customSuffixNum
                }
              >
                {warnContentCalcNum}/{contentMaxNum}
              </span>
            </div>
          </div>
          {!!ttsVoiceFlag && (
            <div className={styles.publicItem}>
              <div className={styles.itemTitle}>请填写TTS语音播报内容:</div>
              <div id="text-Content2" className={styles.itemContent2}>
                <div
                  className={styles.textContent1}
                  onPaste={this.onEditorStatePaste}
                  id="text-area3"
                  onCompositionStart={() => {
                    this.setState({
                      compositionTypingFlag: true,
                    });
                  }}
                  onCompositionEnd={() => {
                    this.setState({
                      compositionTypingFlag: false,
                    });
                  }}
                  onKeyDown={(e) => {
                    e.keyCode === 13 && e.preventDefault(); //  禁止回车事件，影响字数统计
                  }}
                  onInput={() => {
                    this.setState({
                      contentTypingFlag: true,
                    });
                    setTimeout(() => {
                      this.handleContentText('text-area3', 'text-area4', 'tts');
                    });
                  }}
                  onBlur={() => {
                    this.setState(
                      {
                        compositionTypingFlag: false,
                        contentTypingFlag: false,
                      },
                      () => {
                        this.handleContentText('text-area3', 'text-area4', 'tts');
                      },
                    );
                  }}
                  contentEditable
                  placeholder={`请输入最多${contentMaxNum}个字的语音播报内容`}
                ></div>
                <div
                  onPaste={(e) => {
                    e.preventDefault();
                  }}
                  id="text-area4"
                  className={styles.textContent2}
                ></div>
                <span className={styles.customSuffixNum}>
                  {ttsContentCalcNum}/{contentMaxNum}
                </span>
              </div>
            </div>
          )}
          <div className={styles.remarkContent}>
            <div>说明:</div>
            <div>1、车机告警内容、TTS语音播报内容支持填写系统参数；</div>
            <div>
              2、系统参数包括：【商户客服电话】、【未启动天数】、【逾期天数】、【离开管控区域天数】、【T-BOX失联天数】；
            </div>
            <div>3、系统参数占位字数：【商户客服电话】占14位、所有的天数占3位；</div>
            <div>4、跛行或锁车时，仅告警内容、TTS语音播报内容生效，规则中的其他项无效。</div>
          </div>
        </div>
      </Modal>
    );
  }
}
